/*
 * Copyright 2015 Alan.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package me.alanz.screencapture.tool;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import javafx.scene.image.PixelWriter;
import javafx.scene.image.WritableImage;
import javax.imageio.ImageIO;

/**
 * created on 2015-6-15 11:40:05
 *
 * @author Alan
 */
public class ImageTool {

    /**
     * 储存为一个文件,为PNG格式
     *
     * @param image
     * @param file
     * @throws java.io.IOException
     */
    public static void saveAsPNG(BufferedImage image, File file) throws IOException {
        ImageIO.write(image, "PNG", file);
    }

    /**
     * 储存为一个JPEG格式图像文件
     *
     * @param image
     * @param file
     * @throws java.io.IOException
     */
    public static void saveAsJPEG(BufferedImage image, File file) throws IOException {
        ImageIO.write(image, "JPEG", file);
    }

    /**
     * 写入一个OutputStream
     *
     * @param image
     * @param format
     * @param out
     * @throws java.io.IOException
     */
    public static void saveAs(BufferedImage image, String format, OutputStream out) throws IOException {
        ImageIO.write(image, format, out);
    }

    /**
     * 将BufferedImage(AWT)转换为WritableImage(JavaFX)
     *
     * @param bf
     * @return
     */
    public static WritableImage convert(BufferedImage bf) {
        WritableImage wr = null;
        if (bf != null) {
            wr = new WritableImage(bf.getWidth(), bf.getHeight());
            PixelWriter pw = wr.getPixelWriter();
            for (int x = 0; x < bf.getWidth(); x++) {
                for (int y = 0; y < bf.getHeight(); y++) {
                    pw.setArgb(x, y, bf.getRGB(x, y));
                }
            }
        }
        return wr;
    }
}
